// 云函数入口文件
const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

exports.main = async (event, context) => {
  const db = cloud.database();
  const _ = db.command;
  const wxContext = cloud.getWXContext();
  
  // 开启事务
  const transaction = await db.startTransaction();
  
  try {
    // 1. 查询匹配记录（精确匹配）
    const query = {
      _openid: wxContext.OPENID,
      fileIDs: _.in([event.fileID])
    };
    
    if (event.strictMode) {
      query.fileIDs = event.fileID; // 严格模式要求完全匹配
    }

    const record = await transaction.collection('medical_analysis')
      .where(query)
      .get();

    // 2. 验证数据
    if (record.data.length === 0) {
      await transaction.rollback();
      return { 
        success: true, 
        deletedCount: 0,
        message: '未找到匹配记录' 
      };
    }

    if (record.data.length > 1) {
      cloud.logger().warn('发现重复记录', { 
        fileID: event.fileID, 
        records: record.data.map(r => r._id) 
      });
    }

    // 3. 执行删除
    const delRes = await transaction.collection('medical_analysis')
      .doc(record.data[0]._id)
      .remove();

    // 4. 提交事务
    await transaction.commit();

    return { 
      success: true,
      deletedCount: delRes.stats.removed,
      recordId: record.data[0]._id
    };

  } catch (err) {
    // 事务回滚
    try {
      await transaction.rollback();
    } catch (rollbackErr) {
      cloud.logger().error('事务回滚失败:', rollbackErr);
    }
    
    // 分类错误处理
    if (err.errCode === 'DATABASE_PERMISSION_DENIED') {
      err.message = '无数据库写入权限';
    }
    
    return { 
      success: false,
      error: err.message,
      code: err.errCode || 'INTERNAL_ERROR'
    };
  }
};